package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"reflect"
	"syscall"
	"time"
)

// 遍历目录
func walkDir(path string, walkFn func(path string, f os.FileInfo, ss bool, file_type_int uint32)) error {
	info, err := os.Stat(path)
	if err != nil {
		return err
	}
	type Win32FileAttributeData struct {
		FileAttributes uint32
		CreationTime   syscall.Filetime
		LastAccessTime syscall.Filetime
		LastWriteTime  syscall.Filetime
		Size           int64
		IsDirectory    bool
	}
	var data syscall.Win32FileAttributeData
	// 解析JSON到结构体
	bytes, _ := json.Marshal(info.Sys())
	err = json.Unmarshal([]byte(bytes), &data)
	fmt.Println("datadata", data)
	fmt.Println("datadata", data.FileAttributes)
	file_type_int := data.FileAttributes
	if err != nil {
		log.Fatal(err)
	}
	file_isDir := info.IsDir()
	// info.Mode()
	fmt.Println("sys", info.Sys())
	fmt.Println("sys", reflect.TypeOf(info.Sys()))
	walkFn(path, info, file_isDir, file_type_int)
	if info.IsDir() {
		files, err := ioutil.ReadDir(path)
		if err != nil {
			return err
		}
		for _, file := range files {
			err = walkDir(filepath.Join(path, file.Name()), walkFn)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func main() {

	// 调用walkDir函数，并传入一个匿名函数来处理遍历到的每个文件或目录
	// workdir := "C:/Users/Administrator/Desktop/doctopdf"
	// soffice_path := "C:/Program Files/LibreOffice/program/soffice.exe"
	var soffice_path_1 string
	var soffice_path_2 string
	var soffice_path string
	var workdir string
	fmt.Print("请输入soffice的完整路径,例如:C:/Program Files/LibreOffice/program/soffice.exe: (请输入空格前字符)")
	fmt.Scanln(&soffice_path_1)
	fmt.Print("请输入soffice的完整路径,例如:C:/Program Files/LibreOffice/program/soffice.exe:  (请输入空格后字符)")
	fmt.Scanln(&soffice_path_2)
	soffice_path = soffice_path_1 + " " + soffice_path_2

	fmt.Print("请输入要转换的目录，例如:C:/Users/Administrator/Desktop/doctopdf: ")
	fmt.Scanln(&workdir)
	fmt.Println("您输入的soffice_path是:", soffice_path)
	fmt.Println("您输入的workdir是:", workdir)
	fmt.Println("开始", time.Now())
	// soffice_path = "C:/Program Files/LibreOffice/program/soffice.exe"
	// workdir = "D:/Users/chenx/Desktop/培训会议材料"
	err := walkDir(workdir, func(path string, f os.FileInfo, file_isDir bool, file_type uint32) {
		fmt.Printf("Found file or directory: %s\n", path)
		fmt.Printf("Found file or directory: %v\n", file_isDir)
		// if (file_type == 2){
		// 	fmt.Printf("这是一个隐藏文件")
		// 	continu
		// }
		paths, _ := filepath.Split(path)
		// fmt.Println("paths", paths)
		// fmt.Println("fileName", fileName)
		// if false {
		if !file_isDir && file_type != 2 {
			//是文件，需要转
			cmd := exec.Command(soffice_path, "--convert-to", "pdf:writer_pdf_Export", path, "--outdir", paths)
			// 运行命令，并获取输出
			output, err := cmd.CombinedOutput()
			if err != nil {
				panic(err)
			}
			// 打印输出结果
			fmt.Println(string(output))
		}

	})
	if err != nil {
		fmt.Printf("Error walking the directory: %v\n", err)
	}

	fmt.Println("结束", time.Now())
}
